<template>
  <div class="table-page">
    <!-- 上传按钮 -->
    <el-button type="primary" icon="el-icon-upload2" size="mini">上传检测报告</el-button>
    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px" :row-key="row => row.id" >
      <el-table-column label="序号" align="center" width="80">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="mcode" label="物料编码/名称" align="center"/>
      <el-table-column prop="gs1" label="GS1编码" align="center"/>
      <el-table-column prop="batchNum" label="批次号" align="center"/>
      <el-table-column prop="type" label="物料属性" align="center"/>
      <el-table-column prop="spec" label="物料规格" align="center"/>
      <el-table-column prop="warmarea" label="温区" align="center"/>
      <el-table-column prop="num" label="采购数量" align="center"/>
      <el-table-column prop="price" label="采购单价" align="center"/>
      <el-table-column prop="total" label="金额(元)" align="center"/>
      <el-table-column prop="productDate" label="生产日期" align="center"/>
      <el-table-column prop="note" label="备注" align="center"/>
      <!-- 其他列不变... -->
      <el-table-column prop="notQualifiedNum" label="不合格数" align="center">
        <template #default="scope">
          <el-input
            v-model.number="scope.row.notQualifiedNum" 
            size="mini"                                
            type="number"                              
            min="0"                                    
            :max="scope.row.num - (scope.row.qualifiedNum || 0)"
          ></el-input>  
        </template>
      </el-table-column>
      <el-table-column prop="qualifiedNum" label="合格数" align="center"/>
      
      <el-table-column prop="qualifiedRate" label="合格率" align="center"/>
      <el-table-column prop="inspectUser" label="质检人" align="center">
        <template #default="scope">
          <el-input
            v-model="scope.row.inspectUser"  
            placeholder="请输入质检人"     
            maxlength="20"                
            size="mini"                      
          ></el-input> 
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350" header-align="center">
        <template v-slot="{ row }">
          <el-button type="primary" @click="updateById(row)">更新检测结果</el-button>
          <el-button type="primary">更新图片</el-button>
          <el-button type="primary">更新评价</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { getInspectionById, updateInspectById } from '@/api/arrival/arrival.js'
import { ElMessage } from 'element-plus'

const route = useRoute()
const tableData = ref([])

// 补充：更新检测结果函数
async function updateById(row) {
  try {
  
    // 调用更新接口
    const res = await updateInspectById(row.id,row)
    if (res.code === 200) {
      ElMessage.success('更新成功')
      //更新成功 重新获取数据
      const id=route.query.id
      if(id){
        await init(id)
      }
    } else {
      ElMessage.error(`更新失败：${res.msg}`)
    }
  } catch (error) {
    ElMessage.error(`请求异常：${error.message}`)
  }
}

// 根据到货单id获取质检信息（初始化表格数据）
async function init(arrivalId) {
  try {
    const res = await getInspectionById({ arrivalId });
    if (res.code === 200) {
      // 初始化数据时，确保不合格数、合格数、合格率有默认值（避免NaN）
     tableData.value = res.data.map(item => ({
        ...item,
        notQualifiedNum: item.notQualifiedNum || 0,
        qualifiedNum: item.qualifiedNum || Math.max(0, item.num - (item.notQualifiedNum || 0)),
        // 将yield改为qualifiedRate，避免使用关键字
        qualifiedRate: item.num > 0 ? ((item.qualifiedNum || Math.max(0, item.num - (item.notQualifiedNum || 0))) / item.num).toFixed(2) + '%' : '0.00%'
      }));
    } else {
      ElMessage.error(`获取质检数据失败：${res.msg}`);
    }
  } catch (error) {
    ElMessage.error(`请求异常：${error.message}`);
  }
}

// 页面挂载时初始化
onMounted(() => {
  const id = route.query.id;
  if (!id) {
    ElMessage.warning('未获取到到货单ID');
    return;
  }
  init(Number(id)); // 转数字类型，避免后端接收为字符串
});
</script>

<style scoped>
.table-page {
  padding: 20px;
}
/* 调整输入框样式，避免错位 */
.el-table .el-input--mini {
  width: 100px;
}
</style>
